// components/getuserinfo/getuserinfo.js
const util = require('../../utils/util.js')
const app = getApp()
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    authorizeUserInfo: false
  },
  /*  */
  lifetimes: {
    
  },
  /*  */
  pageLifetimes:{
    show: function(){
      //判断本地缓存
      var userinfo = wx.getStorageSync('userinfo')
      if (userinfo.token) {
        let tmpInfo = app.globalData.extend(app.globalData,userinfo)
        app.globalData = tmpInfo
        app.globalData.authorizeUserInfo = true
        this.setData({
          authorizeUserInfo: app.globalData.authorizeUserInfo
        })
      } else {
        app.globalData.authorizeUserInfo = false
        this.setData({
          authorizeUserInfo: app.globalData.authorizeUserInfo
        })
        //
        wx.showLoading({
          title: '',
          mask: true
        })
        this.wx_login().then(res => {
          return this.user_getSissonkey(res)
        }).then(() => {
          wx.hideLoading()
        }).catch(errMsg => {
          wx.hideLoading()
          wx.showModal({
            title: '提示',
            content: errMsg + '',
            showCancel: false,
            confirmColor: app.globalData.modalConfirmColor
          })
        })
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    getUserInfoFn: function (e) {
      //console.log(e)
      new Promise((resolve, reject)=>{
        if (e.detail.errMsg == 'getUserInfo:ok') {
          //存用户信息
          app.globalData.userInfo = e.detail.userInfo
          app.globalData.authorizeUserInfo = true
          this.setData({
            authorizeUserInfo: app.globalData.authorizeUserInfo
          })
          resolve()
        } else {
          reject('请授权获取用户信息')
        }
      }).then(()=>{
        wx.showLoading({
          title:'',
          mask:true
        })
        return this.user_loginWx()
      }).then(()=>{
        wx.hideLoading()
        let pages = getCurrentPages()
        // if(!app.globalData.mobile){
        //   app.globalData.authorizeUserInfo = false
        //   this.setData({
        //     authorizeUserInfo: app.globalData.authorizeUserInfo
        //   })
        //   wx.switchTab({
        //     url:'/pages/personal/personal'
        //   })
        //   return
        // }
        //刷新当前页面
        pages[0].onShow()
      }).catch(errMsg=>{
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content:`${errMsg}`,
          showCancel: false,
          confirmColor: app.globalData.modalConfirmColor
        })
        app.globalData.authorizeUserInfo = false
        this.setData({
          authorizeUserInfo: app.globalData.authorizeUserInfo
        })
      })
    },
    /* 获取登录用户的后台信息 */
    user_loginWx: function () {
      return new Promise((resolve, reject) => {
        wx.request({
          url: app.globalData.Url + '/loginWxCar',
          method: 'POST',
          header: {
            'content-type': app.globalData.contentType
          },
          data: util.json2Form({
            avatar: app.globalData.userInfo.avatar,  //头像
            nickName: app.globalData.userInfo.nickName,  //昵称
            openid: app.globalData.openid,    //openid
          }),
          success: res => {
            console.log(res)
            /* 
            //存本地
            */
            app.globalData.token = res.data.body.token
            app.globalData.header.cartoken = res.data.body.token
            app.globalData.userid = res.data.body.userid
            app.globalData.mobile = res.data.body.mobile?res.data.body.mobile:''
            //console.log(app.globalData)
            //存本地
            wx.setStorageSync('userinfo', app.globalData);
            resolve()
          },
          fail: err => {
            reject('获取与登录用户对应的后台信息失败')
          }
        })
      })
    },/* wx.login */
    wx_login: function () {
      return new Promise((resolve, reject) => {
        wx.login({
          success: res => {
            if (res.errMsg === 'login:ok') {
              // 发送 res.code 到后台换取 openId, sessionKey, unionId
              resolve(res)
            } else {
              reject(res.errMsg)
            }
          },
          fail: err => {
            reject('wx.login失败')
          }
        })
      })
    },
    /* 从后台获取openid和sesion_key */
    user_getSissonkey: function (data) {
      //console.log(data)
      return new Promise((resolve, reject) => {
        app.globalData.code = data.code
        wx.request({
          url: app.globalData.Url + '/getSissonkey',
          method: 'POST',
          header: {
            'content-type': app.globalData.contentType
          },
          data: util.json2Form({
            code: data.code,  //
            type: app.globalData.miniProType //车主端小程序
          }),
          success: res => {
            console.log(res.data)
            if (res.data.code == '1') {
              let tmpData = JSON.parse(res.data.body)
              app.globalData.session_key = tmpData.session_key
              app.globalData.openid = tmpData.openid
              resolve()
            } else {
              reject('从后台获取session_key和openid失败')
            }
          },
          fail: err => {
            reject('从后台获取session_key和openid失败')
          }
        })
      })
    },
  }
})
